﻿
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using XYAC.Framework.MonitorTireMaterialManual.Extensions;

namespace XYAC.Framework.MonitorTireMaterialManual.Context
{
    public class CurrentReportContext : ReportContext
    {
        private bool isEnsureCreate;

        public CurrentReportContext(IOptionsMonitor<AppConfig> options, ILogger<CurrentReportContext> logger) : base()
        {
            AppConfig = options;
            Logger = logger;
            if (AppConfig.CurrentValue.IsUseCustomizePlanDate == true && AppConfig.CurrentValue?.CustomizePlanDate.HasValue == true)
            {
                var tempDate = AppConfig.CurrentValue?.CustomizePlanDate.Value.Date;
                Date = DateOnly.FromDateTime(tempDate.Value);
            }
            else
            {
                Date = DateOnly.FromDateTime(DateTime.Now);
            }
        }
        public bool IsEnsureCreate
        {
            get
            {
                if (!isEnsureCreate)
                {
                    isEnsureCreate = Database.EnsureCreated();
                }
                return isEnsureCreate;
            }
        }

        public IOptionsMonitor<AppConfig> AppConfig { get; }
        public ILogger Logger { get; }
        public DateOnly Date { get; private set; }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            if (!optionsBuilder.IsConfigured)
            {
                optionsBuilder.UseSqlite(AppConfig?.CurrentValue?.LocalReportConnectionStringTemplate.Replace("{DateNow}", Date.ToString("yyyy-MM-dd")));
            }
        }
    }
}
